<template>
  <!-- 添加组织 弹窗 -->
  <el-dialog :title="isEdit ? '编辑组织' : '新增组织'" v-model="dialogVisible">
    <el-form ref="formRef" class="p-3" :rules="rules" :model="form" label-width="80px">
      <el-form-item label="组织名称" prop="departmentName">
        <el-input v-model="form.departmentName" placeholder="请输入组织名称" />
      </el-form-item>
      <el-form-item label="展示顺序" prop="orderNum">
        <el-input-number v-model="form.orderNum" :min="1" :max="100" />
      </el-form-item>
      <el-form-item label="组织备注" prop="remark">
        <el-input :rows="2" type="textarea" maxlength="255" show-word-limit v-model="form.remark" placeholder="请输入组织备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineEmits, defineProps } from "vue";
import { addDepartment, updateDepartment, getDepartmentById } from "@/api/modules/department";
import { ElMessage } from "element-plus";

const props = defineProps({
  id: {
    type: String,
    default: ""
  }
});

const dialogVisible = ref(false);
const formRef = ref(null);
const form = ref({
  departmentName: "",
  orderNum: 1,
  remark: "",
  pid: ""
});
const rules = {
  departmentName: [{ required: true, message: "组织名称不能为空", trigger: "blur" }],
  orderNum: [{ required: true, message: "展示顺序不能为空", trigger: "blur" }]
};
const isEdit = ref(false);
const emit = defineEmits(["cancel", "confirm"]);

const handleCancel = () => {
  emit("cancel");
  dialogVisible.value = false;
};

const handleConfirm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (!isEdit.value) {
        form.value.pid = props.id;
      }
      const apiCall = isEdit.value ? updateDepartment : addDepartment;
      apiCall(form.value).then(res => {
        if (res.code === 200) {
          emit("confirm");
          ElMessage.success(isEdit.value ? "编辑成功！" : "添加成功！");
          dialogVisible.value = false;
          formRef.value.resetFields();
        }
      });
    }
  });
};

const openDialog = id => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  dialogVisible.value = true;
  if (id) {
    isEdit.value = true;
    getDepartmentById(id).then(res => {
      form.value = res.data;
    });
  } else {
    isEdit.value = false;
    form.value = {
      departmentName: "",
      orderNum: 1,
      remark: "",
      pid: ""
    };
  }
};

defineExpose({
  openDialog
});
</script>
